import cache from '../../../utils/cache.js'
import im from '../../../utils/im.js'
Page({

  /**
   * 页面的初始数据
   */
  y: 420, // 页面客服图标y的值
  x: 300, // 页面客服图标x的值
  caculated: false, //是否已经计算
  data: {
    imgUrls: [
    ],
    allDepartments: [

    ],
    twoDepartments: [

    ],
    operationInfo: {
      total: 0,
      operationList: [
        {
          name: '待付款',
          orderNum: 0
        },
        {
          name: '待审核',
          orderNum: 0
        },
        {
          name: '待上传数据',
          orderNum: 0
        }
      ]
    },
    depNum: 1,
    pid: "",
    dialogShow: false,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    currentIndex: 0,
    x: 300,
    y: 420,
    scrollLeft: 0, // 滚动距离
    animationData: {},// 动画参数对象
    pageHeight: wx.getSystemInfoSync().windowHeight + 10000,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    needHelp: false
  },
  callKF: function () { // 聊天
    // 加loading解决im连接缓慢问题
    console.log('正在连接IM……')
    if (!cache.get('_team_list')) {
      wx.showLoading({
        title: '正在连接IM……',
        mask: true
      });
      var appUserInfo = wx.getStorageSync('userInfo');
      console.log(appUserInfo);
      this.imInstance = im.setOptions({
        account: appUserInfo.accid,
        token: appUserInfo.token,
        onsessions: (ss) => {
          cache.set('_current_ss', ss);
          cache.set('_navigate_place', 'kf');
        // wx.navigateTo({
        //   url: '../../message/chat/chat' // 不带id为客服
        // })
        }
      }).getInstance()
    } else {
      wx.navigateTo({
        url: '../../message/chat/chat' // 不带id为客服
      })
    }
  },
  makeACall () { // 打电话
    wx.makePhoneCall({
      phoneNumber: '4009608600' // 仅为示例，并非真实的电话号码
    })
  },
  caculateScrollPageHeight () { // 计算动态高度
    var me = this
    if (me.caculated) return
    console.log('可用高度',wx.getSystemInfoSync().windowHeight)
    wx.createSelectorQuery().selectAll('.department-choose-container').boundingClientRect(function(rects){
      rects.forEach(function(rect){
        console.log('rect', rect.bottom)
        me.setData({
          pageHeight: rect.bottom
        })
        me.caculated = true
        rect.id      // 节点的ID
        rect.dataset // 节点的dataset
        rect.left    // 节点的左边界坐标
        rect.right   // 节点的右边界坐标
        rect.top     // 节点的上边界坐标
        rect.bottom  // 节点的下边界坐标
        rect.width   // 节点的宽度
        rect.height  // 节点的高度
      })
    }).exec()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    this.getData();
    // console.log('获得全局token', getApp().globalData)
  },
  cfChange (e) { // 客服图片改变位置
    // console.log('客服图片改变位置', e)
    this.y = e.detail.y
    this.x = e.detail.x
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('版本号',wx.getSystemInfoSync());
    console.log('测试movable-view', wx.canIUse('swiper.next-margin'))
    wx.eventBus.on('loginSuccess',()=>{
        this.getOperationInfo()
    })
  },
  onPageScroll: function (e) { // 页面滚动
    // console.log('e.detail', e.scrollTop)
    // this.setData({
    //   y: this.y + e.scrollTop,
    //   x: this.x
    // })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    cache.set('canShowModal', true);
    this.getOperationInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 用户点击tab
   */
  onTabItemTap(item) {
    console.log(item.index);
    console.log(item.pagePath);
    console.log(item.text)
  },
  /**
   * 获取页面信息
   */
  getFirstRoomList:function(){
    var self = this;
    var item = self.data.allDepartments[self.data.currentIndex]
    var pid = item.value;
    var params = {
      pid: pid
    }
    self.setData({
      pid: pid,
      currentIndex: 0
    })
    self.getTwolevles(params, item)
  },
  getData: function () {
    var self = this;

    self.data.count = 0;

    wx.showLoading({
      title: '',
    })

    /**
     * 获取所有科室
     */
    wx.request({
      url: wx.envConfig.host + '/department/findAll',
      data: {

      },
      success: function (result) {
        console.log('request success', result)
        ++self.data.count;
        self.stopFresh();
        var arr = [];
        if (result.data && result.data.datas.list.length > 0) {
          result.data.datas.list.forEach((it) => {
            arr.push({
              name: it.name,
              value: it.id,
              img_logo: it.img_logo ? wx.envConfig.filePath + '/' + it.img_logo : '../../../resource/pic/def_chat_avatar.jpg',
              sonNum: it.sonNum, isOpen: it.isOpen
            })
          })
        }
        self.setData({
          allDepartments: [].concat(arr)
        })
        /**
        * 获取第一个一级科室的二级科室列表
        * 
        */
        self.getFirstRoomList()
      },

      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
        wx.stopPullDownRefresh()
      }
    })
    /**
     *  获取轮播图
     */
    wx.request({
      url: wx.envConfig.host + '/system/findCarouselFigureListPage',
      data: {

      },
      method: 'POST',
      success: function (result) {
        // console.log('request success', result)

        ++self.data.count;
        self.stopFresh();

        var tempImgUrs = [];
        for (var index in result.data.datas.list) {
          var item = result.data.datas.list[index];
          item['img_url'] = wx.envConfig.filePath + item.img_path;
          tempImgUrs.push(item);
        }
        self.setData({
          imgUrls: tempImgUrs
        })
      },

      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  imgError (e) { // 对无法显示的图片的处理,index,重置。
    console.log('````````````````````````````````',e)
  },
  /**
   * 停止刷新
   */
  stopFresh: function () {
    if (this.data.count == 2) {
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }
  },
  departScroll(e) {
    console.log('触发滚动')
  },
  /**
   * 点击一级科室
   */
  clickItem: function (event) {
    console.log('11111', event);
    var self = this;
    var item = event.currentTarget.dataset.item;
    if (item.isOpen != '1') {
      wx.showToast({
        title: '敬请期待'
      })
      return
    } 
    var currentIndex = event.currentTarget.dataset.index;
    // console.log(item)
    if (currentIndex !== this.data.currentIndex) {
      // 测试scrollLeft
      var animation = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 1000,
        timingFunction: "ease",
        delay: 0
      });
      this.animation = animation;
      var offsetX = currentIndex * -164;
      animation.translateX(offsetX).step();
      this.setData({
        animationData:animation.export()
      });
      setTimeout(() =>{
        // 空动画
        animation = wx.createAnimation({
          transformOrigin: "50% 50%",
          duration: 100,
          timingFunction: "ease",
          delay: 0
        });
        animation.step();
        this.setData({
          scrollLeft: -offsetX,
          animationData: animation.export()
        });
        console.log('当前滚动距离',this.data.scrollLeft);
      },0)
    }
    var pid = item.value;
    this.setData({
      pid: pid,
      currentIndex: currentIndex
    })
    var params = {
      pid: pid
    }
    self.getTwolevles(params, item)
  },
  /**
   * 点击一级科室搜索对应的二级科室
   */
  getTwolevles: function (params, item) {
    var self = this;
    if (+item.sonNum > 0) {
      var url = wx.envConfig.host + '/department/findAllByPid' + "?params=" + JSON.stringify(params);
      wx.showLoading({
        title: '正在查询子科室...',
        mask: true
      })
      wx.request({
        url: url,
        success: function (result) {
          console.log('request success', result)
          wx.hideLoading();
          var arr = [];
          result.data.datas.list.forEach((it) => {
            arr.push({
              name: it.name, value: it.id, img_logo: wx.envConfig.host + '/uploadFile' + '/' + it.img_logo, sonNum: it.sonNum, isOpen: it.isOpen
            })
          })
          self.setData({
            twoDepartments: [].concat(arr)
          })
          self.caculateScrollPageHeight();
          wx.stopPullDownRefresh()
        },
        fail: function ({ errMsg }) {
          console.log('request fail', errMsg)
          wx.stopPullDownRefresh()
        }
      });
      this.setData({
        dialogShow: true
      })
    }else{
      // 暂时注掉，逻辑要改
      self.setData({
        twoDepartments: [{name: '点击查看', value: item.value, primaryName: item.name}]
      })
      console.log(item)
      // this.checkDepartment(item);
    }
  },

  /**
   * 点击二级科室
   */
  clickCell: function (event) {

    this.setData({
      dialogShow: false
    });
    var item = event.currentTarget.dataset.item;
    console.log('二级科室',item);
    this.checkDepartment(item);
  },

  /**
   * 跳转到选购服务
   */
  checkDepartment: function (item) {
    if (item.primaryName) {
      item.name = item.primaryName
    }
    var url = '../category/category?id=' + item.value + '&pid=' + this.data.pid + '&name=' + item.name;
    wx.navigateTo({
      url: url
    })
  },

  /**
   * 点击二级科室弹窗的关闭按钮
   */
  closeDialog: function (event) {
    this.setData({
      dialogShow: false
    })
  },
  /*
   * 轮播图跳转外链
   */
  clickHorse: function (event) {
    var item = event.currentTarget.dataset.item;
    var url = '../homehtml/homehtml?url_path=' + item.url_path + '&title=' + item.name;
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 点击客服图标
   */
  customService: function () {
    let self = this
    self.setData({
      needHelp: !self.data.needHelp
    })
    console.log('needhelp', self.data.needHelp)
  },
  // 获取订单操作信息
  getOperationInfo () {
    var me = this
    wx.request({
      url: wx.envConfig.host+'/order/getOrderIds?params=' + JSON.stringify({}) + '&cookiez=' + wx.getStorageSync('cookiez'),
      method: 'POST',
      success: function (res) {
        console.log('res```', res)
        if (res.data.error_code === "Y10000") {
          var data = res.data.datas
          var operationInfo = {
            total: data.un_examine.length + data.un_pay.length + data.un_upload.length,
            operationList: [
              {
                name: '待付款',
                orderNum: data.un_pay.length,
                id: data.un_pay
              },
              {
                name: '待审核',
                orderNum: data.un_examine.length,
                id: data.un_examine
              },
              {
                name: '待上传数据',
                orderNum: data.un_upload.length,
                id: data.un_upload
              }
            ]
          }
          me.setData({
            operationInfo: operationInfo
          })
        }
      },
      fail: function ({ errMsg }) {
        console.log('request fail', errMsg)
      }
    })
  },
  // 跳转到订单
  linkToOrderList (e) {
    var info = e.currentTarget.dataset.info
    console.log('info', info)
    var index
    if (info.name == '待审核') {
      index = 2
    } else {
      index = 1
    }
    if (info.orderNum == 1) {
      wx.navigateTo({
        url: '../../order/orderDetail/orderDetail?id=' + e.currentTarget.dataset.info.id[0]
      })
    } else {
      wx.navigateTo({
        url: '../../order/orderList/orderList?index=' + index
      })
    }
    // 待付款 => 待付款 index = 1
    // 待审核 => 设计中 index = 2
    // 待上传数据 => 待付款 index = 1
  },
  onTabItemTap (item) {
    console.log('点击了首页的导航栏')
    return
  }
})